const express = require('express');
const router = express.Router();

const path = require('path')
const fs = require('fs')
const time = require('time-stamp')
const svg = require('svg-captcha')

const formidable = require('formidable')

router.get('/login',(req,res)=>{
    res.sendFile(path.join(__dirname,'view/login.html'))
})

router.get('/register',(req,res)=>{
    res.sendFile(path.join(__dirname,'view/register.html'))
})

let dir = path.join(__dirname,'persons.json')
let data = fs.readFileSync(dir,'utf-8')
data = JSON.parse(data)

router.post('/login',(req,res,next)=>{
    let {tel,pass} = req.body;
    if(!tel || !pass){
        next('用户名或密码不能为空')
        return;
    }

    let s = data.find(item=>item.username == tel && item.password == pass);

    if(s){
        res.send({code:200,msg:'登录成功'})
        return;
    }
    next('用户名或密码错误')
})

router.get('/code',(req,res)=>{
    let s = svg.create({
        color:true,
        background:'#eee',
        noise:3
    })
    console.log(s);
    req.session.code = s.text;

    res.type('svg')
    res.send(s.data)
})

router.post('/register',(req,res,next)=>{

let haha = formidable({
    keepExtensions:true,
    uploadDir:path.join(__dirname,'upload')
})  

haha.parse(req,(err,fields,files)=>{
    console.log(err,fields,files);

    let {tel,pass,pass2,yzm} = req.body;
    console.log(tel,pass,pass2,yzm);


    let trueYzm = req.session.code;
    if(yzm.toUpperCase() != trueYzm.toUpperCase()){
        next('验证码不正确');
        return;
        
    }
    console.log(trueYzm);

    if(!tel || !pass || !pass2){
        next('请输入有效内容')
        return;
    }

if(pass != pass2){
    next('两次密码输入不一致')
    return;
}


if(!files.heihei.originalFilename){
    next('请上传有效文件')
    return;
}

let s = data.find(item=>item.username == tel);
if(s){
    next('用户名已存在')
    return;
}

data.push({username:tel,password:pass,time:req.time,url:path.join('upload',files.heihei.newFilename)});
fs.writeFileSync(dir,JSON.stringify(data));
res.send({code:200,msg:'注册成功'})

})

})

module.exports = router;